﻿using MangoMes.Commont.DapperHelps;
using MangoMes.Commont.DTOs;
using MangoMes.Commont.Infrastructures.Interfaces;
using MediatR;

namespace ManagoMes.Read.API.Applications.SellStockSearchRead
{
    public class ProductsSaleSearchHandler : IRequestHandler<ProductsSaleSearchCommand, CodePageDTO<ProductsSaleDTO>>
    {
        private readonly IBateRepository<ProductsSaleDTO> _productssaleDTORepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="productssaleDTORepository"></param>
        public ProductsSaleSearchHandler(IBateRepository<ProductsSaleDTO> productssaleDTORepository)
        {
            _productssaleDTORepository = productssaleDTORepository;
        }
        /// <summary>
        /// 产品销售列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<CodePageDTO<ProductsSaleDTO>> Handle(ProductsSaleSearchCommand request, CancellationToken cancellationToken)
        {
            //连接数据库
            DapperHelper dapper = new DapperHelper();
            string conn = dapper.MangoMesRead;
            //分页查询
            CodePageDTO<ProductsSaleDTO> str = new CodePageDTO<ProductsSaleDTO>();
            var pageNum = (request.pageIndex - 1) * request.pageSize;
            //实体DTO
            ProductsSaleDTO ssk = new ProductsSaleDTO();
            string sql = $"select * from productssale  inner join productmanage on productssale.ProductManageNode=productmanage.productManageNode inner join warehouselist on productssale.StashId=warehouselist.StashId inner join sellstock on productssale.SellStockNo=sellstock.SellStockNo where productssale.ProductsSaleYesNo=0 and sellstock.SellStockNo='{request.SellStockNo}'";
            var result = _productssaleDTORepository.GetAll(sql, ssk, conn).ToList();
            str.TotalCount = result.Count();
            str.PageCount = (int)Math.Ceiling((result.Count() * 1.0) / request.pageSize);
            result = result.OrderBy(p => p.ProductsSaleId).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
            str.Data = result;
            str.Code = 0;
            return str;
        }
    }
}
